<template>
    <div>
        <h1>用户管理</h1>
        <el-button @click="openCreateDialog">新增用户</el-button>
        <el-table :data="users" stripe>
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button v-if="scope.row.username !== 'admin'" @click="openEditDialog(scope.row)"
                        :disabled="scope.row.username === 'admin'">编辑</el-button>
                    <el-button v-if="scope.row.username !== 'admin'" @click="openDeleteDialog(scope.row.id)"
                        :disabled="scope.row.username === 'admin'">删除</el-button>
                    <el-button v-if="scope.row.username !== 'admin'" @click="openResetPasswordDialog(scope.row.id)"
                        :disabled="scope.row.username === 'admin'">重置密码</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增用户对话框 -->
        <el-dialog v-model="createDialogVisible" title="新增用户" width="20%">
            <el-form :model="newUser" ref="createFormRef">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="newUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="newUser.password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createUser">确定</el-button>
            </template>
        </el-dialog>

        <!-- 编辑用户对话框 -->
        <el-dialog v-model="editDialogVisible" title="编辑用户">
            <el-form :model="editUser" ref="editFormRef">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editUser.username"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updateUser">确定</el-button>
            </template>
        </el-dialog>

        <!-- 删除用户确认对话框 -->
        <el-dialog v-model="deleteDialogVisible" title="确认删除">
            <span>确定要删除该用户吗？</span>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="deleteUser">确定</el-button>
            </template>
        </el-dialog>

        <!-- 重置密码对话框 -->
        <el-dialog v-model="resetPasswordDialogVisible" title="重置密码">
            <el-form :model="resetPasswordForm" ref="resetPasswordFormRef">
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="resetPasswordForm.newPassword" type="password"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="resetPassword">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { userApi } from '../../api/userApi'; // 导入封装好的API

// 用户类型定义
interface User {
    id: number;
    username: string;
    password?: string;
}

// 响应式数据
const users = ref<User[]>([]);
const createDialogVisible = ref(false);
const newUser = ref({ username: '', password: '' });
const editDialogVisible = ref(false);
const editUser = ref<User>({ id: 0, username: '' });
const deleteDialogVisible = ref(false);
const deleteUserId = ref<number | null>(null);
const resetPasswordDialogVisible = ref(false);
const resetPasswordForm = ref({ newPassword: '' });
const resetPasswordUserId = ref<number | null>(null);

// 用户操作逻辑
const fetchUsers = async () => {
    try {
        users.value = await userApi.fetchUsers();
    } catch (error) {
        ElMessage.error('获取用户列表失败');
        console.error('Error fetching users:', error);
    }
};

const openCreateDialog = () => {
    createDialogVisible.value = true;
    newUser.value = { username: '', password: '' };
};

const createUser = async () => {
    try {
        await userApi.createUser(newUser.value);
        createDialogVisible.value = false;
        await fetchUsers();
        ElMessage.success('用户创建成功');
    } catch (error) {
        ElMessage.error('用户创建失败');
        console.error('Error creating user:', error);
    }
};

const openEditDialog = (user: User) => {
    editDialogVisible.value = true;
    editUser.value = { ...user };
};

const updateUser = async () => {
    if (!editUser.value.id) return;

    try {
        await userApi.updateUser(editUser.value.id, { username: editUser.value.username });
        editDialogVisible.value = false;
        await fetchUsers();
        ElMessage.success('用户更新成功');
    } catch (error) {
        ElMessage.error('用户更新失败');
        console.error('Error updating user:', error);
    }
};

const openDeleteDialog = (id: number) => {
    deleteDialogVisible.value = true;
    deleteUserId.value = id;
};

const deleteUser = async () => {
    if (!deleteUserId.value) return;

    try {
        await userApi.deleteUser(deleteUserId.value);
        deleteDialogVisible.value = false;
        await fetchUsers();
        ElMessage.success('用户删除成功');
    } catch (error) {
        ElMessage.error('用户删除失败');
        console.error('Error deleting user:', error);
    }
};

const openResetPasswordDialog = (id: number) => {
    resetPasswordDialogVisible.value = true;
    resetPasswordUserId.value = id;
    resetPasswordForm.value = { newPassword: '' };
};

const resetPassword = async () => {
    if (!resetPasswordUserId.value || !resetPasswordForm.value.newPassword) return;

    try {
        await userApi.resetPassword(resetPasswordUserId.value, resetPasswordForm.value.newPassword);
        resetPasswordDialogVisible.value = false;
        ElMessage.success('密码重置成功');
    } catch (error) {
        ElMessage.error('密码重置失败');
        console.error('Error resetting password:', error);
    }
};

onMounted(() => {
    fetchUsers();
});
</script>

<style scoped lang="scss">
:deep(.el-dialog) {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0 !important;
    border-radius: 10px;
}
</style>